package com.leetcode.studyplan.algorithm.introduction.secondday;

public class L_189_RotateArray {

    /**
     * 最后一个测试用例没过。超出了时间限制
     * 把时间复杂度降至O(n)，并且空间复杂度为O(1)
     * @param nums
     * @param k
     * @return
     */
    public int[] rotate(int[] nums, int k) {
        int length = nums.length;
        if (nums == null || length <= 1) {
            return nums;
        }

        int realK = k % length;

        for (int i = realK; i > 0; i--) {
            int tmp = nums[length - i];
            for (int j = length - i; j > realK - i; j--) {
                nums[j] = nums[j - 1];
            }
            nums[realK - i] = tmp;
        }
        return nums;
    }

    /**
     * 采用翻转数组的思路
     * 1. 翻转整个数组
     * 2. 翻转 [0,k % length - 1]的数组
     * 3. 翻转 [k % length - 1, length - 1]
     * @param nums
     * @param k
     * @return
     */
    public void rotate1(int[] nums, int k) {
        k = k % nums.length;
        reverse(nums, 0 , nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k , nums.length - 1);
    }

    public void reverse(int[] nums, int start, int end) {

        while (start < end) {
            int tmp = nums[start];
            nums[start] = nums[end];
            nums[end] = tmp;
            start++;
            end--;
        }
    }

    public static void main(String[] args) {

//        int[] nums = {1,2,3,4,5,6,7};
        int[] nums = {-1,-100,3,99};
        int k = 2;
        L_189_RotateArray rotateArray = new L_189_RotateArray();
        rotateArray.rotate1(nums, k);
        System.out.println(nums);
    }
}
